<?php
/**
 * Created by PhpStorm.
 * User: baich
 * Date: 2019/1/17
 * Time: 10:14
 */

namespace app\common;


use Yii;

class SendSms
{
    public $url = 'http://113.108.155.146:9616/message/pushSms.htm'; //接口地址
    public $send = array(
        'channel'=>'WYYX',  //消息平台分配的应用ID
        'corporationCode'=>'1',   //弃用，保持不变
        'businessName'=>'1'		//弃用，保持不变
    );
    public $sign='1XRAvYZeELq/6Z2xoY4j'; //消息平台分配的应用KEY
    public function postCurl($url,$data){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);  //定义超时3秒钟
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        //执行curl
        $output = curl_exec($ch);
        //关闭curl
        curl_close($ch);

        return $output;
    }

    //发送函数
    //$mobileStr 接收手机号，可接受多个手机号，手机号以英文“,”分隔
    //$content 短信内容
    public function sendInfo($mobileStr,$content){

        //配置中获取请求地址
        $url = $this->url;
        //手机号字符串 多个手机号 以,符号隔开

        if(empty($mobileStr) || empty($content)){
            return false;
        }
        //数组转换
        $mobileArr = explode(',',$mobileStr);

        //手机号认证处理
        foreach($mobileArr as $val){
            //去除空格
            $mobile = str_replace(' ', '',$val);
            //去除中划线-
            $mobile = preg_replace("/-/is","",$mobile);
            //截取字符串长度
            if(strlen($mobile)>11){
                $mobile = substr($mobile,strlen($mobile)-11,11);
            }
            //手机号码验证
            if (preg_match("/^1[34578]{1}\d{9}$/",$mobile)){
                $user_mobile[] = $mobile;
            }
        }

        if(count($user_mobile) == 0){
            return false;
        }

        $send = $this->send;
        //按键值排序
        ksort($send);
        //生成签名
        $sign = $this->generateSign($send);
        $send['sign'] = $sign;
        $send['mobiles'] = implode(',',$user_mobile);
        $send['content'] = $content;

        //发送请求
        $result = $this->postCurl($url,$send);
        //$result = json_decode($result,true);
        echo $result;
        // if($result['stateCode'] != '0000' || empty($result)){
        // return false;
        // }
        //return $result;
    }
    // public function sendInfo7(){
    // $this->sendInfo('15013152975','中油APP项目发送短信测试！');
    // }
    public function generateSign($send){
        $sign = $this->sign;
        foreach($send as $key=>$val){
            $sign.=$key;
            $sign.=$val;
        }

        //md5加密
        $sign = md5($sign);
        //加密后转换为大写
        $sign = strtoupper($sign);
        //签名返回
        return $sign;
    }
}
